﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Store.DateModel;

/// <summary>
/// Summary description for StoreApplicationService
/// </summary>
public class StoreApplicationService 
{
    #region ProductsOperations

    public IList<Product_Categories> GetProductCategories()
    {
        IList<Product_Categories> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (db.Product_Categories.OrderBy(c => c.category_name)).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load ALL Categories - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    public IList<Brand>              GetAllProductBrands()
    {
        IList<Brand> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (db.Brands.OrderByDescending(b => b.brand_name)).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load ALL Brands - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    public IList<ProductView>        GetAllProducts()
    {
        IList<ProductView> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from prod in db.ProductViews
                         where prod.size_type=="small"
                         select prod).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load ALL Products - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    public IList<ProductView>        GetProductsByCategory(int categoryID)
    {
        IList<ProductView> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from Products in db.ProductViews
                         where Products.size_type == "small"
                         where Products.CategoryID == categoryID
                         select Products).ToList();

            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load ALL Products - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    public IList<ProductView>        GetProductsByBrand(int brandID)
    {
        IList<ProductView> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from Products in db.ProductViews
                         where Products.size_type == "small"
                         where Products.BrandID == brandID
                         select Products).ToList();

            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load ALL Products - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    public IList<ProductModel>       GetMostPopularProducts(int nop)
    {
        IList<ProductModel> query;
        using (StoreDBEntitiesConnection db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from ProductOrders in db.Orderd_Products
                         join SelectedProducts in db.ProductViews on ProductOrders.ProductID equals SelectedProducts.ID
                         where SelectedProducts.size_type == "small"
                         group ProductOrders by new
                         {
                             id = SelectedProducts.ID,
                             name = SelectedProducts.name,
                             img_url = SelectedProducts.image_url,
                             price = SelectedProducts.price,
                             old_price = SelectedProducts.old_price,
                             views = SelectedProducts.views,
                             rating = SelectedProducts.rating,
                             is_promotion = SelectedProducts.is_promotion
                         } into grp
                         select new ProductModel
                         {
                             ID = grp.Key.id,
                             image_url = grp.Key.img_url,
                             price = grp.Key.price,
                             old_price = grp.Key.old_price,
                             views = grp.Key.views,
                             rating = grp.Key.rating,
                             name = grp.Key.name,
                             quantity = grp.Sum(o => o.quantity),
                             is_promotion = grp.Key.is_promotion
                         } into orderdgrp
                         where orderdgrp.quantity > 0
                         orderby orderdgrp.quantity descending
                         select orderdgrp).Take(nop).ToList();

            }
            catch (Exception exp)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load Popular Items - " + exp.Message.ToString(), exp);
            }
        } return query;
    }
    public IList<ProductModel>       GetNewestProducts(int nop)
    {
        IList<ProductModel> query;
        using (var db = new Store.DateModel.StoreDBEntitiesConnection())
        {
            try
            {
                query = (from Products in db.ProductViews
                         where Products.size_type == "small"
                         select new ProductModel
                         {
                             ID = Products.ID,
                             image_url = Products.image_url,
                             price = Products.price,
                             old_price = Products.old_price,
                             name = Products.name,
                             views = Products.views,
                             rating = Products.rating,
                             created_at = Products.created_at,
                             is_promotion = Products.is_promotion
                         } into prod
                         orderby prod.created_at descending
                         select prod).Take(nop).ToList();

            }
            catch (Exception exp)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Retrieve Newest Products - " + exp.Message.ToString(), exp);
            }
        } 
        return query;
    }
    public IList<ProductModel>       GetMostViewedProducts(int nop)
    {
        IList<ProductModel> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from Products in db.ProductViews
                         where Products.size_type == "small"
                         select new ProductModel
                         {
                             ID = Products.ID,
                             image_url = Products.image_url,
                             price = Products.price,
                             old_price = Products.old_price,
                             name = Products.name,
                             views = Products.views,
                             rating = Products.rating,
                             is_promotion = Products.is_promotion
                         }).OrderByDescending(o => o.views).Take(nop).ToList();

            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load MostViewed Prod - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    #endregion

    #region Product Atributs
    //public IList<GetAtributsForProduct_Result> GetAtributsForProduct(int prodID)
    //{
    //    IList<GetAtributsForProduct_Result> query;
    //    using (var db = new StoreDBEntitiesConnection())
    //    {
    //        try
    //        {
    //            query = (db.GetAtributsForProduct(prodID)).ToList();
    //        }
    //        catch (Exception ex)
    //        {
    //            throw new Exception("ERROR:ServiceLayer: Unable to load ProductDetails - " + ex.Message.ToString(), ex);
    //        }
    //    }
    //    return query;
    //}
    //public IList<Atribute_Type> GetAtributsForProductCategory(int categoryID)
    //{
    //    IList<Atribute_Type> query;
    //    using (var db = new StoreDBEntitiesConnection())
    //    {
    //        try
    //        {
    //            query = (from atr in db.Atribute_Type
    //                     where atr.CategoryID == categoryID
    //                     select atr).ToList();
    //        }
    //        catch (Exception ex)
    //        {
    //            throw new Exception("ERROR:ServiceLayer: Unable to load ProuctAtributs - " + ex.Message.ToString(), ex);
    //        }
    //    }
    //    return query;
    //}

    #endregion

    #region Product Promotion
    public IList<ProductModel>      GetPromotionProducts(int nop)
    {
        IList<ProductModel> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from prom in db.ProductViews
                         where prom.is_promotion == true
                         where prom.size_type == "small"
                         select new ProductModel
                         {
                             ID = prom.ID,
                             name = prom.name,
                             image_url = prom.image_url,
                             short_description = prom.short_description
                         }).Take(nop).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to load Promotion Products - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    public ProductView              GetBestOffer()
    {
        ProductView query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from prod in db.ProductViews
                         where prod.size_type =="small"
                         orderby prod.price ascending 
                         select prod ).First();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to load Best Offer - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    #endregion
    
    #region Wishlist
    public IList<WishlistModel> GetAllWishlists()
    {
        IList<WishlistModel> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from wl in db.Wishlists
                         join user in db.aspnet_Users on wl.UserID equals user.UserId
                         select new WishlistModel
                         {
                             ID = wl.ID,
                             user = user.UserName,
                             wishlist_titlu = wl.wishlist_titlu,
                             description = wl.description,
                             created_on = wl.created_on

                         }).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load All Wishlists - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    public IList<ProductModel> GetWishlistDetails(int wlID)
    {
        IList<ProductModel> query;
        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                query = (from PinW in db.Products_in_Wishlists
                         join prod in db.Products on PinW.ProductID equals prod.ID
                         join img in db.Images on prod.ID equals img.ProductID
                         join wl in db.Wishlists on wlID equals wl.ID
                         where img.size_type == "small"
                         select new ProductModel
                         {
                             ID = prod.ID,
                             image_url = img.image_url,
                             name = prod.name,
                             price = prod.price,
                             old_price = prod.price,
                             rating = prod.rating,
                             quantity = PinW.quantity
                         }).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Load All Wishlists - " + ex.Message.ToString(), ex);
            }
        }
        return query;
    }
    #endregion

 
    #region CRUD (creare, read, update, delete)
    //TODO add CRUD operations
    public void IncrementViewToProduct(int prodID)
    {
        //var ip_address = Session["ip_address"] as string;

        using (var db = new StoreDBEntitiesConnection())
        {
            try
            {
                var prod = (from p in db.Products
                            where p.ID == prodID
                            select p).First();
                prod.views++;
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR:ServiceLayer: Unable to Increment view - " + ex.Message.ToString(), ex);
            }
        }
    }
    #endregion

    #region "Comments"
    public void AddProductComments(string prodID, string CommentMessage, string CommentTitle, string UserID)
    {
  

      using (var db = new StoreDBEntitiesConnection())
      {
        try
        {
          var query = from c in db.Comments where c.comment_body == CommentMessage && c.comment_title == CommentTitle select c;
          if (query.Count() != 0)
            return;

          Comment com = new Comment();
          com.comment_body = CommentMessage;
          com.comment_title = CommentTitle;
          com.UserID =  Guid.Parse(UserID);
          db.Comments.AddObject(com);
          db.SaveChanges();
          
          Product_Comments pc = new Product_Comments();
          pc.ProductID = Convert.ToInt32(prodID);
          pc.CommentID = com.ID;
          db.Product_Comments.AddObject(pc);
          db.SaveChanges();
        }
        catch (Exception ex)
        {
          throw new Exception("ERROR:ServiceLayer: Unable to Increment view - " + ex.Message.ToString(), ex);
        }
      }
    }
    
    #endregion
}